var express = require("express");
var router = express.Router();
// var async = require("async");
const user_login = require("../model/user_login");
const user_check = require("../model/user_check");

router.post("/api/v1/registration", function (req, res, next) {
  try {
    console.log(req.body)
    user_login.find({
      phone: req.body.phone
    }, async function (err, doc) {
      if (!err) {
        if (doc.length > 0) {
          res.json({
            code: 201,
            message: "账号已经存在"
          });
        } else {
          var user = await user_check.findOne({
            name: req.body.name,
            company: req.body.company,
          }).exec()
          console.log(user)
          if (user) {
            if (req.body.phone == user.phone1 || req.body.phone == user.phone2) {
              user_login.create({
                  name: req.body.name,
                  password: req.body.password,
                  phone: req.body.phone,
                  position: req.body.position,
                  department: req.body.department,
                  registration_time:new Date(),
                  audit: true
                },
                function (err, doc) {
                  console.log(err);

                  if (err) return next(err);
                  res.jsonp({
                    code: 200,
                    data: doc,
                    message: "验证通过，可直接进行登录"
                  });
                }
              );
            } else {
              user_login.create({
                  name: req.body.name,
                  password: req.body.password,
                  phone: req.body.phone,
                  position: req.body.position,
                  department: req.body.department,
                  registration_time:new Date(),
                },
                function (err, doc) {
                  console.log(err);

                  if (err) return next(err);
                  res.jsonp({
                    code: 200,
                    data: doc,
                    message: "您的注册信息与集团人员备案信息不一致，请等待人工审核。"
                  });
                }
              );
            }

          } else {
            user_login.create({
                name: req.body.name,
                password: req.body.password,
                phone: req.body.phone,
                position: req.body.position,
                department: req.body.department,
                registration_time:new Date(),
              },
              function (err, doc) {
                console.log(err);

                if (err) return next(err);
                res.jsonp({
                  code: 200,
                  data: doc,
                  message: "注册成功，请耐心等待审核"
                });
              }
            );
          }

        }
      } else {
        return next(err);
      }
    });
  } catch (error) {
    res.status(500).send(error);
  }
});

// 导出模块（在 app.js 中引入）
module.exports = router;
